package eip.chapter1.example;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Simple class that transforms the CSV file to an XML File
 * 
 * @author NL24167
 */
public class CSVToXMLTransformer {

  /** locations in the csv */
  private final static int FIRST_NAME = 0;
  private final static int LAST_NAME = 1;
  private final static int BASE_SALARY = 2;
  private final static int SALES_AMOUNT = 3;
  private final static int PROVISION_PERC = 4;

  /** xml related values */
  private final static String XML_NS = "http://www.companyA.org/salary";
  private final static String XML_REPORT = "report";
  private final static String XML_PERSONS = "persons";
  private final static String XML_PERSON = "person";
  private final static String XML_FIRSTNAME = "firstName";
  private final static String XML_LASTNAME = "lastName";
  private final static String XML_SALARY = "salary";
  private final static String XML_BASE = "base";
  private final static String XML_VALUE = "value";
  private final static String XML_PROVISION = "provision";
  private final static String XML_SUM = "sum";
  private final static String XML_PERCENTAGE = "percentage";

  /**
   * Simple method that transforms the supplied CSV string into an 
   * XML Document.
   * 
   * @param csvData the data to transform
   * @return an XML document.
   */
  public Document transformCSV(String csvData) {
    Document result = DocumentHelper.createDocument();
    Element root = DocumentHelper.createElement(XML_REPORT);
    root.addNamespace("", XML_NS);
    Element persons = root.addElement(XML_PERSONS);
    String[] lines = csvData.split("\n");
    for (int i = 0; i < lines.length; i++) {
      // get all the fields from this line
      String[] fields = csvData.split(",");
      // and put them into a person element
      Element person = DocumentHelper.createElement(XML_PERSON);
      Element firstName = person.addElement(XML_FIRSTNAME);
      firstName.setText(fields[FIRST_NAME]);
      Element lastName = person.addElement(XML_LASTNAME);
      lastName.setText(fields[LAST_NAME]);
      // the salary element is more complex
      Element salary = DocumentHelper.createElement(XML_SALARY);
      Element base = DocumentHelper.createElement(XML_BASE);
      base.addAttribute(XML_VALUE, fields[BASE_SALARY]);
      Element prov = DocumentHelper.createElement(XML_PROVISION);
      prov.addAttribute(XML_SUM, fields[SALES_AMOUNT]);
      prov.addAttribute(XML_PERCENTAGE, fields[PROVISION_PERC]);
      salary.add(base);
      salary.add(prov);
      // complete and add the person to the list
      person.add(salary);
      persons.add(person);
    }
    result.add(root);
    return result;
  }
}
